package work.timejay.seleniums.ad2la;

import com.google.common.collect.Lists;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.therapi.runtimejavadoc.repack.com.eclipsesource.json.JsonArray;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import work.timejay.bo.CopyCategoryBO;
import work.timejay.bo.CopyCategoryItemBO;
import work.timejay.entity.CopyBooksCatalogue;
import work.timejay.properties.ChromeDriverProperties;
import work.timejay.service.CopyBooksCatalogueService;
import work.timejay.utils.CommonHttpUtils;
import work.timejay.utils.FileUtils;

import java.io.Console;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @className:Ad2laUtils.java
 * @author:王文杰
 * @version:1.0.0
 * @description:ad2la采集工具类
 * @createTime 2023年12月09日 17:09:00
 */
@Slf4j
@Component
public class Ad2laUtils {

    @Autowired
    private CopyBooksCatalogueService copyBooksCatalogueService;


    @Autowired
    private FileUtils fileUtils;

    @Autowired
    private ChromeDriverProperties chromeDriverProperties;

    /**
     * 获取类目数据
     */
    public void copyCategory(String type, int categoryCount, String url) {
        boolean status = true;
        JSONArray array = new JSONArray();
        StringBuilder urlBuilder = new StringBuilder();
        for (int i = 1; i <= categoryCount; i++) {
            urlBuilder.append(url);
            String parameter = "?sortid=" + type + "&page=" + i;
            urlBuilder.append(parameter);
            String targetUrl = urlBuilder.toString();
            String response = CommonHttpUtils.okhttp3(targetUrl);
            if (null == response) {
                log.error("request failed with url ------->{}", url);
                status = false;
            }
            JSONArray jsonArray = JSONUtil.parseArray(response);
            array.addAll(jsonArray);
            urlBuilder.setLength(0);
        }
        CopyBooksCatalogue bean = new CopyBooksCatalogue();
        bean.setTitle("采集网站：" + url + "类型：" + type + "数量：" + categoryCount);
        bean.setType(type);
        bean.setContent(array.toString());
        bean.setPageCount((long) categoryCount);
        bean.setStatus(status);
        bean.setId(IdWorker.getId());
        bean.setCreateTime(LocalDateTime.now());

        copyBooksCatalogueService.save(bean);
    }

    /**
     * 解析类目数据
     */
    public List<CopyCategoryBO> analysisOfCategoriesData() {
        List<CopyBooksCatalogue> booksCatalogueList = copyBooksCatalogueService.findInfoList();
        List<CopyCategoryBO> items = new ArrayList<CopyCategoryBO>();
        booksCatalogueList.forEach(e -> {
            JSONArray jsonArray = JSONUtil.parseArray(e.getContent());
            jsonArray.forEach(item -> {
                JSONObject json = JSONUtil.parseObj(item);
                String title = json.getStr("articlename");
                String author = json.getStr("author");
                String intro = json.getStr("intro");
                String url_img = json.getStr("url_img");
                String url_list = json.getStr("url_list");
                try {
                    byte[] bytes = IOUtils.toByteArray(new URL(url_img));
                    if (bytes.length > 0) {
                        url_img = fileUtils.upload(bytes, IdWorker.get32UUID(), ".jpg");
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                CopyCategoryBO bo = new CopyCategoryBO();
                bo.setTitle(title);
                bo.setCoverPath(url_img);
                bo.setAuthor(author);
                bo.setBookDesc(intro);
                bo.setType(Long.valueOf(e.getType()));
                bo.setSourceLink("https://www.ad2la.com" + url_list);
                items.add(bo);
            });
        });
        return items;
    }

    public List<CopyCategoryItemBO> copyCategoryItemData(String url) {
        log.info("url ----->{}", url);
        System.setProperty(chromeDriverProperties.getDriver(), chromeDriverProperties.getDriverPath());
        List<CopyCategoryItemBO> boList = new ArrayList<CopyCategoryItemBO>();
        //解决linux 下无桌面报错
        ChromeOptions options = new ChromeOptions();
        options.setPageLoadStrategy(PageLoadStrategy.EAGER);
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--headless");
        options.addArguments("--no-sandbox");  //“–no - sandbox”参数是让Chrome在root权限下跑
        options.addArguments("--disable-gpu");  //谷歌文档提到需要加上这个属性来规避bug
        options.addArguments("--disable-dev-shm-usage");  //fix:DevToolsActivePort file doesn't exist
        //options.addArguments("--remote-debugging-port=9222");  // DevToolsActivePort file doesn't
        //options.addArguments("window-size=1920x1080"); //指定浏览器分辨率
        WebDriver driver = new ChromeDriver(options);
        //driver.manage().window().setSize(new Dimension(1920,1080));
        driver.get(url);

        List<WebElement> elements = driver.findElements(By.tagName("dd"));
        log.info("elements数量 ------>{}", elements.size());
        Long i = 1L;
        for (int j = 1; j < elements.size(); j++) {
            WebElement e = elements.get(j);
            String title = null;
            String itemHref = null;
            try {
                title = e.getText();
                itemHref = e.findElement(By.tagName("a")).getAttribute("href");
            } catch (Exception exception) {
                exception.printStackTrace();
                log.info("目录标题，网址获取异常");
                continue;
            }
            if (itemHref.contains("javascript")) {
                log.info("error url ---->{}", itemHref);
                e.click();
                continue;
            }
            CopyCategoryItemBO bo = new CopyCategoryItemBO();
            bo.setTitle(title);
            bo.setOrderNum(i);
            bo.setSourceLink(itemHref);

            boList.add(bo);
            i++;
        }
        log.info("boList数量 ------>{}", boList.size());
        driver.quit();
        return boList;
    }

    public String copyBooksChapter(WebDriver driver, String url) throws Exception {
        log.info("url ----->{}", url);
        driver.get(url);
        String content = driver.findElement(By.id("chaptercontent")).getText();
        if (StringUtils.isNotBlank(content)) {
            content = content.replace("点此报错", "");
            content = content.replace("加入书签", "");
            content = content.replace("』", "");
            content = content.replace("『", "");
            content = content.replace("https://m.ad2la.com", "");
            content = content.replace("https://www.ad2la.com", "");
            content = content.replace("请收藏本站：", "");
            content = content.replace("请收藏本站", "");
            content = content.replace("阿达小说网手机版：", "");
            content = content.replace("阿达小说网手机版", "");
            content = content.replace("\\n\\n", "<br/>");
            return content;
        }
        return null;
    }
}
